package fr.upmc.i3s.upmcontact.views.fragments;

import org.jsoup.Jsoup;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;
import fr.upmc.i3s.upmcontact.R;
import fr.upmc.i3s.upmcontact.backend.BackEndBridgeImpl;
import fr.upmc.i3s.upmcontact.contents.User;
import fr.upmc.i3s.upmcontact.tools.MobileDataUtils;
import fr.upmc.i3s.upmcontact.tools.PreferencesManager;
import fr.upmc.i3s.upmcontact.tools.StringUtils;
import fr.upmc.i3s.upmcontact.views.FragmentController;
import fr.upmc.i3s.upmcontact.views.dialogs.NoConnectivityDialog;
import fr.upmc.i3s.upmcontact.views.fragments.models.IFragmentModel;
import fr.upmc.i3s.upmcontact.views.fragments.models.PageFragmentModel;

public class SettingsFragment extends PageFragmentModel implements IFragmentModel {
	
	private static final String TAG = "SettingsFragment";
	
	private FragmentController fragmentController;
	private static volatile SettingsFragment INSTANCE;
	
	private TextView tvLoggedAs;
	private TextView tvLogout;
	private CheckBox cbKeepLogged;
	private TextView tvCheckUpdate;
	private TextView tvStatsIncidents;
	private TextView tvStatsLost;
	private TextView tvStatsFound;
	private TextView tvAboutDevs;
	private TextView tvAboutLicences;
	private TextView tvAboutSupport;
	private TextView tvAboutBlog;
	
	private TextView tvFeetLeft;
	private TextView tvFeetRight;
	private ImageView ivArrowLeft;
	private ImageView ivArrowRight;
	
	public static SettingsFragment getInstance() {
		if(INSTANCE == null) {
			SettingsFragment fragment = new SettingsFragment();
		    Bundle bundle = new Bundle(4);
		    bundle.putInt(EXTRA_LAYOUT_FRAGMENT, R.layout.fragment_settings);
		    bundle.putInt(EXTRA_HEAD_ICON, R.drawable.ic_menu_setting_white);
		    bundle.putInt(EXTRA_HEAD_TEXT, R.string.title_fragment_settings);
		    fragment.setArguments(bundle);
		    INSTANCE = fragment;
		}
	    return INSTANCE;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return super.onCreateView(inflater, container, savedInstanceState);
	}
	
 	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.initFragmentViews();
		this.fragmentController = (FragmentController) getActivity();
		fetchViews();
		customizeViews();
		setListeners();
	}
 	
 	@Override
 	public void fetchViews() {
 		this.tvLoggedAs = (TextView) this.getView().findViewById(R.id.textView_connected_as);
 		this.tvLogout = (TextView) this.getView().findViewById(R.id.textView_logout);
 		this.cbKeepLogged = (CheckBox) this.getView().findViewById(R.id.checkBox_auto_login);
 		this.tvCheckUpdate = (TextView) this.getView().findViewById(R.id.textView_check_update);
 		this.tvStatsIncidents = (TextView) this.getView().findViewById(R.id.textView_stats_incidents);
 		this.tvStatsLost = (TextView) this.getView().findViewById(R.id.textView_stats_lost);
 		this.tvStatsFound = (TextView) this.getView().findViewById(R.id.textView_stats_found);
 		this.tvAboutDevs = (TextView) this.getView().findViewById(R.id.textView_developers);
 		this.tvAboutLicences = (TextView) this.getView().findViewById(R.id.textView_licences);
 		this.tvAboutSupport = (TextView) this.getView().findViewById(R.id.textView_contact);
 		this.tvAboutBlog = (TextView) this.getView().findViewById(R.id.textView_blog);
 		this.tvFeetLeft = (TextView) this.getView().findViewById(R.id.textView_feet_text_left);
 		this.tvFeetRight = (TextView) this.getView().findViewById(R.id.textView_feet_text_right);
 		this.ivArrowLeft = (ImageView) this.getView().findViewById(R.id.imageView_feet_arrow_left);
 		this.ivArrowRight = (ImageView) this.getView().findViewById(R.id.imageView_feet_arrow_right);
 	}
 	
 	@Override
 	public void customizeViews() {
		User user = BackEndBridgeImpl.getInstance(getActivity()).getCurrentUser();
		if(user!=null) {
			String username = BackEndBridgeImpl.getInstance(getActivity()).getCurrentUser().getUsername();
			this.tvLoggedAs.setText(
					fragmentController.getString(R.string.display_connected_as)+" "+
					StringUtils.toProperNoun(username));
		} else {
			this.tvLoggedAs.setText(R.string.unknown);
		}
		user = PreferencesManager.getSignInSettings(fragmentController);
		if(user!=null && user.isKeepLogged()) {
			this.cbKeepLogged.setChecked(true);
		} else {
			this.cbKeepLogged.setChecked(false);
		}
 		this.tvStatsIncidents.setText(fragmentController.getString(R.string.display_stats_incidents)+" "+PreferencesManager.retrieveIncidentReportStatistics(fragmentController));
 		this.tvStatsLost.setText(fragmentController.getString(R.string.display_stats_lost)+" "+PreferencesManager.retrieveLostReportStatistics(fragmentController));
 		this.tvStatsFound.setText(fragmentController.getString(R.string.display_stats_found)+" "+PreferencesManager.retrieveFoundReportStatistics(fragmentController));
 		this.tvFeetLeft.setText("");
 		this.tvFeetRight.setText("");
 		this.ivArrowLeft.setVisibility(View.GONE);
 		this.ivArrowRight.setVisibility(View.GONE);
 	}
 	
 	@Override
 	public void setListeners() {
 		this.cbKeepLogged.setOnCheckedChangeListener(onKeepLoggedChangeListener); 
 		this.tvLogout.setOnClickListener(onLogoutClickListener);
 		this.tvCheckUpdate.setOnClickListener(onCheckUpdateClickListener);
 		this.tvAboutDevs.setOnClickListener(onAboutDevsClickListener);
 		this.tvAboutLicences.setOnClickListener(onAboutLicencesClickListener);
 		this.tvAboutSupport.setOnClickListener(onAboutSupportClickListener);
 		this.tvAboutBlog.setOnClickListener(onAboutBlogClickListener);
 	}
 	
 	
 	  ////////////////
 	 // ASYNCTASKS //
 	////////////////

 	private class CheckUpdateTask extends AsyncTask<Void, Integer, Boolean> {
 		private static final int UPDATE_AVAILABLE = 1;
 		private static final int UPDATE_LATEST = 0;
 		private static final int UPDATE_NOK = -1;
 		ProgressDialog pd;
 		@Override
 		protected void onPreExecute() {
 			pd = new ProgressDialog(fragmentController);
 			pd.setCancelable(false);
 			pd.setTitle(R.string.update_check_title);
 			pd.setMessage(fragmentController.getString(R.string.update_check_msg));
 			pd.show();
 		}
 		@Override
 		protected void onPostExecute(Boolean result) {
 			pd.cancel();
 		}
 		@Override
 		protected Boolean doInBackground(Void... arg0) {
 			try{
 				Looper.prepare();
 				String curVersion = fragmentController.getPackageManager().getPackageInfo("fr.upmc.i3s.upmcontact", 0).versionName; 
 				String newVersion = curVersion;
 				newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + "fr.upmc.i3s.upmcontact" + "&hl=en")
 						.timeout(30000)
 						.userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
 						.referrer("http://www.google.com")
 						.get()
 						.select("div[itemprop=softwareVersion]")
 						.first()
 						.ownText();
 				boolean needUpdate = ((StringUtils.getLongFromString(curVersion) < StringUtils.getLongFromString((newVersion)) ? true : false));
 				Log.i(TAG, "needUpdate=" + needUpdate);
 				if(needUpdate) {
 					publishProgress(UPDATE_AVAILABLE);
 				} else {
 					publishProgress(UPDATE_LATEST);
 				}
 			} catch (Exception e) {
 				Log.e(TAG, "Exception : ",e);
 				publishProgress(UPDATE_NOK);
 			}	
			return true;
 		}
 		@Override
 		protected void onProgressUpdate(Integer... value) {
 			pd.cancel();
 			switch(value[0]) {
 			case UPDATE_AVAILABLE:
				new AlertDialog.Builder(fragmentController)
				.setTitle(R.string.update_available_title)
				.setMessage(R.string.update_available_msg)
				.setNegativeButton(android.R.string.no, null)
				.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						String url = "https://play.google.com/store/apps/details?id=" + "fr.upmc.i3s.upmcontact" + "&hl=en";
						Intent i = new Intent(Intent.ACTION_VIEW);
						i.setData(Uri.parse(url));
						startActivity(i);
					}
				})
				.show();
 				break;
 			case UPDATE_LATEST:
				new AlertDialog.Builder(fragmentController)
				.setTitle(R.string.update_latest_title)
				.setMessage(R.string.update_latest_msg)
				.setPositiveButton(android.R.string.ok, null)
				.show();
 				break;
 			case UPDATE_NOK:
 			default:
				new AlertDialog.Builder(fragmentController)
				.setTitle(R.string.update_nok_title)
				.setMessage(R.string.update_nok_msg)
				.setPositiveButton(android.R.string.ok, null)
				.show();
 				break;
 			}
 		}
 	}
 	
 	
 	  ///////////////
 	 // LISTENERS //
 	///////////////
 	
 	private OnCheckedChangeListener onKeepLoggedChangeListener = new OnCheckedChangeListener() {
		@Override
		public void onCheckedChanged(CompoundButton arg0, boolean checked) {
			if(checked) {
				User user = BackEndBridgeImpl.getInstance(fragmentController).getCurrentUser();
				PreferencesManager.saveSignInSettings(fragmentController, user);
				PreferencesManager.saveSignInSettings(fragmentController, checked);
			} else {
				PreferencesManager.clearSignInSettings(fragmentController);
			}
		}
 	};
 	
 	private OnClickListener onLogoutClickListener = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			new AlertDialog.Builder(getActivity())
			.setTitle(R.string.title_logout)
			.setMessage(R.string.msg_logout)
			.setIcon(R.drawable.ic_logout)
			.setPositiveButton(android.R.string.yes, new Dialog.OnClickListener() {
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					BackEndBridgeImpl.getInstance(getActivity()).logout();
				}
			})
			.setNegativeButton(android.R.string.no, new Dialog.OnClickListener() {
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					// do nothing
				}
			})
			.setCancelable(true).create().show();
		}
 	};
 	
 	private OnClickListener onCheckUpdateClickListener = new OnClickListener() {
 		@Override
 		public void onClick(View v) {
 			if(MobileDataUtils.isNetworkAvailable(fragmentController)) {
 				new CheckUpdateTask().execute();
 			} else {
 				NoConnectivityDialog.build(fragmentController).show();
 			}
		}
 	};
 	
 	private OnClickListener onAboutDevsClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			new AlertDialog.Builder(fragmentController)
			.setTitle(R.string.title_developers)
			.setMessage(Html.fromHtml(getString(R.string.developers)))
			.show();
		}
 	};
 	
 	private OnClickListener onAboutLicencesClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			new AlertDialog.Builder(fragmentController)
			.setTitle(R.string.licences)
			.setMessage(Html.fromHtml(getString(R.string.apache_licences)))
			.show();
		}
 	};
 	
 	private OnClickListener onAboutSupportClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto","anthony.st91@gmail.com", null));
			emailIntent.putExtra(Intent.EXTRA_SUBJECT, "UPMContact-Support");
			startActivity(Intent.createChooser(emailIntent, fragmentController.getString(R.string.email_to_support)));
		}
 	};
 	
 	private OnClickListener onAboutBlogClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			String url = "http://upmcontact.blogspot.fr/";
			Intent i = new Intent(Intent.ACTION_VIEW);
			i.setData(Uri.parse(url));
			startActivity(i);
		}
 	};
 	
}
